<script type="text/javascript">
//<![CDATA[
jQuery(function($){

    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();

    $("#schedule-calendar").fullCalendar({        
        height: 700
        ,header: {
            left: '',
            center: 'title',
            right: 'prev,next today'
        }        
        ,eventClick: function(calEvent, jsEvent, view) {
           eventFromInit();
           eventFormSetting(calEvent);
           $("#post-form-btn").hide();
           $("#view-form-btn").show();
           $("#a-event-post").attr("title","일정상세/수정").click();
        }
        ,editable: true
        ,eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) {
           
            if (confirm("일정 일자를 수정하시겠습니까?")) {
                $.post(scheduleSettings.ajaxurl , {
                    action: "schedule-update-day"
                    ,ev_no:event.id
                    ,ev_startday:event.start.formatDate()
                    ,ev_endday:event.end.formatDate()
                    , _ajax_nonce: scheduleSettings.schedule_update_day_nonce
                }, function(data){
                    if(data.success){                        
                        alert("일정이 수정되었습니다.");
                    }else{
                        alert("일정이 수정되지 않았습니다.");
                        return false;
                    }
                });
            }else{
                revertFunc();
            }

        }
        ,selectable: true
        ,selectHelper: true
        ,select: function selectPeriod(startDate, endDate, allDay, jsEvent, view){
            eventFromInit();
            var eventForm = $("#eventForm");
            var get_cateno = '<?php echo $_GET["sk_cateno"]?>';          
            
            $("#ev_startday", eventForm).val(startDate.formatDate());
            $("#ev_starthour", eventForm).val("09");
            $("#ev_startminute", eventForm).val("00");
            $("#ev_endday", eventForm).val(endDate.formatDate());
            $("#ev_endhour", eventForm).val("18");
            $("#ev_endminute", eventForm).val("00");
            if(get_cateno != ""){
                $("#ev_cateno", eventForm).val(get_cateno);
            }

            $("#view-form-btn").hide();
            $("#post-form-btn").show();
            $("#a-event-post").attr("title","일정등록").click();            
        }
        ,events: '<?php echo WP_PLUGIN_URL;?>/epart-schedule/admin/schedule-admin-data.php?cateno=<?php echo $_GET["sk_cateno"];?>'
        ,columnFormat: {
		month: "dddd"
		,week: 'ddd M/d'
		,day: 'dddd M/d'
        }
	,titleFormat: {
                month: 'yyyy년 MMMM',
		week: "yyyy년 MMMM d[ yyyy]{ '&#8212;'[ MMM] d}",
		day: 'yyyy, MMMM d'
        }
        ,timeFormat: "TTh:mm"
        ,monthNames: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"]
        ,monthNamesShort: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"]
        ,dayNames: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
        ,dayNamesShort: ["일", "월", "화", "수", "목", "금", "토"]
        ,dragOpacity: 0.8
        ,theme:true


    });

    // 폼초기화
    function eventFromInit(){
        var eventForm = $("#eventForm");
        $("#ev_no",eventForm).val("");
        $("#ev_title", eventForm).val("");
        $("#ev_startday", eventForm).val("");
        $("#ev_starthour", eventForm).val("");
        $("#ev_startminute", eventForm).val("");
        $("#ev_endday", eventForm).val("");
        $("#ev_endhour", eventForm).val("");
        $("#ev_endminute", eventForm).val("");
        $("#ev_content", eventForm).val("");
        $("#ev_location", eventForm).val("");
        $("#ev_color", eventForm).val("#3366cc");
        $("#ev_color_preview", eventForm).css("background-color","#3366cc");
        $("#ev_repeat", eventForm).val("");
        $("#ev_cateno", eventForm).val("");
    }

    // 폼값 셋팅
    function eventFormSetting(calEvent){
       var eventForm = $("#eventForm");       

       // 해당 일정 값 뷰 div에 넣기
       if(calEvent.id){
            $("#ev_no",eventForm).val(calEvent.id);
       }
       if(calEvent.title){
            $("#ev_title",eventForm).val(calEvent.title);
       }
       if(calEvent.start){           
            $("#ev_startday",eventForm).val(calEvent.start.formatDate());
            $("#ev_starthour",eventForm).val(calEvent.start.formatDate("HH"));
            $("#ev_startminute",eventForm).val(calEvent.start.formatDate("mm"));
       }
       if(calEvent.end){
            $("#ev_endday",eventForm).val(calEvent.end.formatDate());
            $("#ev_endhour",eventForm).val(calEvent.end.formatDate("HH"));
            $("#ev_endminute",eventForm).val(calEvent.end.formatDate("mm"));
       }
       if(calEvent.location){
            $("#ev_location",eventForm).val(calEvent.location);
       }
       if(calEvent.content){
            $("#ev_content",eventForm).val(calEvent.content);
       }
       if(calEvent.color){
            $("#ev_color",eventForm).val(calEvent.color);
            $("#ev_color_preview", eventForm).css("background-color",calEvent.color);
       }
       if(calEvent.repeat){
            $("#ev_repeat",eventForm).val(calEvent.repeat);
       }
       if(calEvent.cateno){
            $("#ev_cateno",eventForm).val(calEvent.cateno);
       }
    }
    
    //추가
    $("#btn-add").click(function(){

        var eventForm = $("#eventForm")
        
        if(eventFormCheck() == false){
            return false;
        }

        eventForm.attr("action","<?php echo $add_db_url;?>");
    });

    //수정
    $("#btn-update").click(function(){

        var eventForm = $("#eventForm")

        if(eventFormCheck() == false){
            return false;
        }

        eventForm.attr("action","<?php echo $update_db_url;?>");
    });
    
    //삭제
    $("#btn-delete").click(function(){

        var eventForm = $("#eventForm")

        if(!confirm("일정을 삭제하시겠습니까?")){
            return false;
        }

        eventForm.attr("action","<?php echo $delete_db_url;?>");
    });
    
    // 닫기
    $("#btn-close").click(function(){
        $("#TB_closeWindowButton").click();
    });

    // 폼 유효성 검사
    function eventFormCheck(){
        var eventForm = $("#eventForm")

        if(!$("#ev_title",eventForm).val()){
            alert("제목을 입력해주세요");
            return false;
        }

        if(!$("#ev_startday",eventForm).val()){
            alert("시작일을 입력해주세요");
            return false;
        }

        if(!$("#ev_endday",eventForm).val()){
            alert("종료일을 입력해주세요");
            return false;
        }

        // 종료일이 시작일 이후인지 검사
        var startday_arr = $("#ev_startday").val().split("-");        
        var endday_arr = $("#ev_endday").val().split("-");
        var startday_timestamp = Date.UTC(startday_arr[0], startday_arr[1], startday_arr[2], $("#ev_starthour").val(), $("#ev_startminute").val(), 0);
        var endday_timestamp = Date.UTC(endday_arr[0], endday_arr[1], endday_arr[2], $("#ev_endhour").val(), $("#ev_endminute").val(), 0);
        if(startday_timestamp > endday_timestamp){
            alert("종료일이 시작일 이전일 수 없습니다.");
            return false;
        }        
    }

    // color picker 설정
    $('.color-preview').click(function () {
        $(this).prev().click();
    })
    $('.colorpicker_schedule').ColorPicker({
        onChange: function (e, hex) {
            $('.colorpicker_schedule').val('#' + hex);
            $('.colorpicker_schedule').next().css('background', '#' + hex);
        },
        onSubmit: function(hsb, hex, rgb, el) {
            $(el).ColorPickerHide();
        },
        color: '#efefef'
    });

    // datepicker 설정
    $("#ev_startday, #ev_endday").datepicker({
        closeText: '닫기',
        prevText: '이전달',
        nextText: '다음달',
        currentText: '오늘',
        monthNames: ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'],
        monthNamesShort: ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'],
        dayNames: ['일','월','화','수','목','금','토'],
        dayNamesShort: ['일','월','화','수','목','금','토'],
        dayNamesMin: ['일','월','화','수','목','금','토'],
        weekHeader: '주',
        dateFormat: 'yy-mm-dd',
        firstDay: 0,
        isRTL: false,
        showMonthAfterYear: true                
        ,showOn: "both"
        ,buttonImage: userSettings.url + 'wp-content/plugins/epart-common/css/images/btn_i_calendar.gif'
        ,buttonImageOnly: true
        ,changeYear: true
        ,changeMonth: true
        ,gotoCurrent: true
        ,showButtonPanel: true

    });

    //카테고리 추가
    $(".cate-add-btn").click(function(){

        var cate_name = $("input[name^=new_ev_catename]",$(this).parent().prev());

        if(cate_name.val() == ""){
            alert('카테고리명을 입력해주세요');
            cate_name.focus();
            return false;
        }
        
        $.post(scheduleSettings.ajaxurl , {
            action: "schedule-category-add"
            ,ev_catename:cate_name.val()
            , _ajax_nonce: scheduleSettings.schedule_category_add_nonce
        }, function(data){
            if(data.success){
                alert("카테고리가 추가되었습니다.");

                //row없다는 표시하는 tr 숨기기
                if($("#no-row-tr").css("display") != "none"){
                    $("#no-row-tr").hide();
                }
                cate_name.val("");
                $("tbody",$("#event-catogory-table")).append(
                    "<tr>\n\
                            <td>\n\
                                <input type=\"hidden\" id=\"ev_cateno"+data.ev_cateno+"\" name=\"ev_cateno"+data.ev_cateno+"\" value=\""+data.ev_cateno+"\" />\n\
                                <input type=\"text\" id=\"ev_catename"+data.ev_cateno+"\" name=\"ev_catename"+data.ev_cateno+"\" value=\""+data.ev_catename+"\" size=\"40\" />\n\
                            </td>\n\
                            <td>\n\
                                <input type=\"button\" class=\"cate-update-btn\" value=\"수정\" />\n\
                                <input type=\"button\" class=\"cate-del-btn\" value=\"삭제\" />\n\
                            </td>\n\
                        </tr>"
                );
            }else{
                alert("카테고리가 추가되지 않았습니다.");
                return false;
            }
        });

        
    });

    //카테고리 수정
    $(".cate-update-btn").live('click',function(){
        
        var cate_no = $("input[name^=ev_cateno]",$(this).parent().prev()).val();
        var cate_name = $("input[name^=ev_catename]",$(this).parent().prev());

        if(cate_name.val() == ""){
            alert('카테고리명을 입력해주세요');
            cate_name.focus();
            return false;
        }
        
        $.post(scheduleSettings.ajaxurl , {
            action: "schedule-category-update"
            ,ev_cateno:cate_no
            ,ev_catename:cate_name.val()
            , _ajax_nonce: scheduleSettings.schedule_category_update_nonce
        }, function(data){
            if(data.success){
                alert("카테고리가 수정되었습니다.");
            }else{
                alert("카테고리가 수정되지 않았습니다.");
                return false;
            }
        });       
    });

     //카테고리 삭제
    $(".cate-del-btn").live('click',function(){

        var cate_no = $("input[name^=ev_cateno]",$(this).parent().prev()).val();

        $.post(scheduleSettings.ajaxurl , {
            action: "schedule-category-del"
            ,ev_cateno:cate_no
            , _ajax_nonce: scheduleSettings.schedule_category_del_nonce
        }, function(data){
            if(data.success){
                alert("카테고리가 삭제되었습니다.");
            }else{
                alert("카테고리가 삭제되지 않았습니다.");
                return false;
            }
        });

        var tbody_tr_size = $("tr",$(this).closest("tbody")).size();        
        $(this).closest("tr").remove();

        // row 없을 시 보일 tr
        if(tbody_tr_size == 2){
            $("#no-row-tr").show();
        }
    });

    // 카테고리 창에서 수정 발생시 닫기 버튼 교체로 전체 페이지 새로고침 하게 함
    $("body").delegate("#TB_ajaxContent", "click", function(){
        var close_btn = $("#TB_closeWindowButton");
        var is_category = $("#add-catogory-table",$("#TB_ajaxContent")).size();
        
        if(close_btn.attr("href") == "#" && is_category > 0){            
            close_btn.hide();            
            if($("#TB_closeAjaxWindow img").size() == 1){
                $("#TB_closeAjaxWindow").append("<a id=\"my-close-btn\" href=\"#\"><img src=\"../wp-includes/js/thickbox/tb-close.png\" /></a>");
            }
        }
    });

    $("body").delegate("#my-close-btn", "click", function(){
        document.location.replace("<?php echo $list_url;?>");
    });
});
//]]>
</script>

<!--
<div id="search-category">
    <form id="search-category-form" name="search-category-form" method="get" action="?">
    <input type="hidden" name="page" value="<?php echo $_GET['page'];?>" />
    <select id="sk_cateno" name="sk_cateno">
        <option value="">전체</option>
        <?php 
        $get_cateno = $_GET['sk_cateno'];
        foreach ($category_obj as $row){
          $cate_selected = ($get_cateno == $row->ev_cateno) ? " selected=\"selected\"" : "";
       ?>
            <option value="<?php echo $row->ev_cateno;?>"<?php echo $cate_selected;?>><?php echo $row->ev_catename;?></option>
        <?php }?>
    </select>
    <input type="submit" value="선택" />
    </form>
</div>
-->

<div id="schedule-calendar"></div>

<a href="#TB_inline&width=405&height=350&inlineId=event-post" title="일정등록" id="a-event-post" class="thickbox"></a>

<div id="event-post">
    <form id="eventForm" name="eventForm" method="post" action="">
    <input type="hidden" id="ev_no" name="ev_no" size="50" />    
    <?php wp_nonce_field("schedule-add-update"); ?>
    <table id="event-post-table" cellspacing="0">
        <colgroup>
            <col width="40%" />
            <col width="60%" />
        </colgroup>

        <tbody>
            <tr>
                <td cope="col" class="first-column">제목</td>
                <td cope="col">                    
                    <input type="text" id="ev_title" name="ev_title" size="45" />
                </td>
            </tr>
            <tr>
                <td class="first-column">시작일</td>
                <td>
                    <input type="text" id="ev_startday" name="ev_startday" size="17" />
                    <input type="text" id="ev_starthour" name="ev_starthour" size="5">시
                    <input type="text" id="ev_startminute" name="ev_startminute" size="5">분
                </td>
            </tr>
            <tr>
                <td class="first-column">종료일</td>
                <td>
                    <input type="text" id="ev_endday" name="ev_endday" size="17" />
                    <input type="text" id="ev_endhour" name="ev_endhour" size="5">시
                    <input type="text" id="ev_endminute" name="ev_endminute" size="5">분
                </td>
            </tr>
            <tr>
                <td class="first-column">장소</td>
                <td>
                    <input type="text" id="ev_location" name="ev_location" size="45" />
                </td>
            </tr>
            <tr>
                <td class="first-column">내용</td>
                <td>
                    <textarea id="ev_content" name="ev_content" cols="37" rows="5"></textarea>
                </td>
            </tr>
            <tr>
                <td class="first-column">색상</td>
                <td>
                   <input type="text" id="ev_color" class="colorpicker_schedule" name="ev_color" size="40" />
                   <span id="ev_color_preview" class="color-preview" style="background-color: #3eae3e;width:25px;height:30px;">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                </td>
            </tr>
            <!--
            <tr>
                <td class="first-column">반복</td>
                <td>
                    <select id="ev_repeat" name="ev_repeat" class="ev_repeat">
                        <option value="">선택</option>
                        <option value="0">반복없음</option>
                        <option value="1">주간반복</option>
                        <option value="2">월간반복</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td class="first-column">카테고리</td>
                <td>
                    <select id="ev_cateno" name="ev_cateno">
                        <option value="">선택</option>
                        <?php                                
                        foreach ($category_obj as $row){
                          $cate_selected = ($get_cateno == $row->ev_cateno) ? " selected=\"selected\"" : "";
                       ?>
                            <option value="<?php echo $row->ev_cateno;?>"<?php echo $cate_selected;?>><?php echo $row->ev_catename;?></option>
                        <?php }?>
                    </select>
                </td>
            </tr>
            -->
        </tbody>
    </table>
    <div id="view-form-btn">
        <input type="submit" id="btn-update" value="수정" />
        <input type="submit" id="btn-delete" value="삭제" />
    </div>
    <div id="post-form-btn">
        <input type="submit" id="btn-add" value="추가" />
        <input type="button" id="btn-close" value="닫기" />
    </div>
    </form>    
</div>

<div id="add-category">
    <h3>카테고리 추가</h3>
    <form name="add-category-form" id="add-category-form" action="<?php echo $add_category_url;?>" method="post">
    <table id="add-catogory-table" cellspacing="0">
        <colgroup>
            <col width="70%" />
            <col width="30%" />
        </colgroup>

        <thead>
            <tr>
                <th cope="col">카테고리명</th>
                <th cope="col">관리</th>
            </tr>
        </thead>

        <tbody>
            <tr>
                <td>
                    <input type="text" id="new_ev_catename" name="new_ev_catename" value="" size="40" />
                </td>
                <td>
                    <input type="button" class="cate-add-btn" value="추가" />
                </td>
            </tr>
        </tbody>
    </table>
    </form>
    
    <h3 style="margin-top:30px;">카테고리 수정</h3>
    <table id="event-catogory-table" cellspacing="0">
        <colgroup>            
            <col width="70%" />
            <col width="30%" />
        </colgroup>

        <thead>
            <tr>                
                <th cope="col">카테고리명</th>
                <th cope="col">관리</th>
            </tr>
        </thead>

        <tbody>
            <?php foreach ($category_obj as $row){?>
            <tr>                
                <td>
                    <input type="hidden" id="ev_cateno<?php echo $row->ev_cateno;?>" name="ev_cateno<?php echo $row->ev_cateno;?>" value="<?php echo $row->ev_cateno;?>" />
                    <input type="text" id="ev_catename<?php echo $row->ev_cateno;?>" name="ev_catename<?php echo $row->ev_cateno;?>" value="<?php echo $row->ev_catename;?>" size="40" />
                </td>
                <td>                    
                    <input type="button" class="cate-update-btn" value="수정" />
                    <input type="button" class="cate-del-btn" value="삭제" />
                </td>
            </tr>
            <?php }?>
            
            <tr id="no-row-tr" <?php if($category_obj != null){echo 'style="display:none"';}?>>
                <td colspan="2">
                    등록된 카테고리가 없습니다.
                </td>
            </tr>           
        </tbody>
    </table>    
</div>
